// pages/general_edit/general_edit.js
let listBehavior = require('../../behavior/list')
Page({
    behaviors: [ listBehavior, ],
    /**
     * 页面的初始数据
     */
    data: {
      tableid: '',  //模块id
      rowid: '',  //行id
      isDisplay: true,
      status: 'edit',  //页面状态：edit,add
      approveFlag: false,
      aprRowid: '',

      repeatIndex: null, //查重覆盖行

    },

  /**
   * 保存数据
   * @param e
   * 1、保存数据成功
   *
   * 2、判断新增保存
   * 2.1、获取模块参数
   * 2.2、判断该模块是否启用审批
   * 2.3、启用了审批，插槽中显示审批组件，提交审批
   * 2.4、取消提交，新增数据则保留当前页面，清空数据
   * 2.5、取消提交，返回上一页
   * 2.6、没有启用审批，新增数据则保留当前页面，清空数据
   * 2.7、没有启用审批，返回上一页
   *
   * 3、判断编辑保存，保留当前页面，页面改为只读状态
   */
    bindSave(e){
      wx.showLoading({mask: true});
      let data = e.detail.data;
      wx.$each(data.entity,(key,val)=>{
        if (key.indexOf(';') >= 0){
          delete data.entity[key]
        }
      });
      this.data.saveData = data;
      this.data.isShow = e.detail.isShow;
      if (this.data.status === 'add'){
        this.checkRepeat(data.entity).then(()=>{
          this.saveData({table:{
            table_id: this.data.tableid,
            entitys: [data]
          }});
        });
        return;
      }
      this.saveData({table:{
        table_id: this.data.tableid,
        entitys: [data]
      }});
    },
    //新增提交审批后操作
    bindNewApprove(){
      let {newApprove,newShow} = this.data;
      if (newApprove) { //新增审批
        if (newShow) {  //新增数据
          this.setData({
            rowid: 0,
            status: 'add',
            aprRowid: 0,
            approveFlag: false,
            newApprove: false,
            newShow: false
          });
          return
        }
        //跳转到前一个页面
        wx.navigateBack({
          delta:1,//前一个页面
        })
      }else {
      //  240523 增加获取下一审批记录，跳转下一条
        this.getNextApprovalData().then((data) =>{
          if (data){
            wx.showModal({
              title: '下一审批记录',
              content: '是否跳转下一审批记录进行审批?',
              success: (res) => {
                if(res.confirm) {
                  // this.data.tableLayout
                  this.setData({
                    rowid: data?.row_id,
                    aprRowid: data?.row_id,
                    tableid: data?.table_id
                  })
                }
              },
            })
          }
        })
      }
    },
    //审批有数，不可编辑
    aprState(e){
      let state = e.detail
      this.setData({aprState: state});
    },
    saveData(post,is_overwrite){
      return new Promise(resolve => {
        wx.showLoading({mask:true});
        wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(async res=>{
          if (res.errcode != 0){
            resolve();
            return
          }
          let data = res.data.row[0] && res.data.row[0].entity;

          wx.$toast("保存成功！");
          this
            .refreshList();

          let pageStatus = this.data.status,
            isShow = this.data.isShow;
          if (pageStatus === 'add'){  //当前新增界面
            //获取审批信息
            await this.getEntityParam(this.data.tableid);
            if (is_overwrite){
              wx.navigateBack({ //跳转到前一个页面
                delta:1,//前一个页面
              });
              resolve();
              return
            }

            if (this.data.entityParam.is_verify) {  //当前编辑界面、已启用审批
              this.setData({
                aprRowid: data[0].row_id,
                approveFlag: true,
                newApprove: !this.data.aprState,
                aprState: true,
                newShow: isShow,
                isDisplay: true
              });
              /*wx.pageScrollTo({
                scrollTop: 10000,
                duration:1500
              })*/
            }else if (isShow){ //没有启用审批、新增数据
              this.setData({
                rowid: 0,
                status: 'add'
              })
            }else { //没有启用审批、返回上一页
              wx.navigateBack({ //跳转到前一个页面
                delta:1,//前一个页面
              })
            }
            resolve();
            return
          }
          if (isShow){
            this.setData({
              rowid: 0,
              status: 'add'
            });
            resolve();
            return
          }
          let obj = {isDisplay: true}
          if (this.data.entityParam.is_verify){
            obj.approveFlag = true

            /*obj.aprRowid = data[0].row_id
            obj.approveFlag = true
            obj.newApprove = !this.data.aprState
            obj.aprState = true
            obj.newShow = isShow*/
          }
          this.setData(obj);
          resolve(data);
        })
      })
    },

    //查重
    checkRepeat(obj){
      return new Promise(async resolve => {
        let fieldInfo = await this.getFieldData(this.data.tableid) || [],
          repeatField = [], //查重字段信息集合
          btns = {
            is_addnew: [],  //允许新建
            is_overwrite: [], //允许覆盖
            is_notsave: [], //不允许保存
          },
          userid = wx.getStorageSync('user_id'),
          departmentid = wx.getStorageSync('department_id'),
          searchWhere = [], //重复筛选条件
          {tableid} = this.data;

        let input_time = '',
          owner_id = '',
          Order_No = '';
        //循环判断字段信息是否启用查重
        wx.$each(fieldInfo, (i, item)=>{

          if ('input_time' === item.field_id) {
            input_time = item;
          }
          if ('owner_id' === item.field_id) {
            owner_id = item;
          }
          if ('Order_No' === item.field_id) {
            Order_No = item;
          }

          if (item.is_duplicate_check) {
            !['input_time', 'owner_id', 'Order_No'].includes(item.field_id) && repeatField.push(item);

            searchWhere.push({ CompareWith: tableid + '.' + item.field_id, Operator: "=", CompareValue: obj[item.field_id], or: 1 });

            let arr = ['is_addnew', 'is_overwrite', 'is_notsave'];
            wx.$each(arr, (ind, ite) =>{
              //判断按钮权限
              if (item[ite]) {
                let roles = item[ite + '_roles'];
                try {
                  roles = JSON.parse(roles);
                } catch (e) { }
                let user = roles && roles.user,
                  department = roles && roles.department,
                  isUser = user && user.find(function (ite2) {
                    return ite2.id == userid;
                  }),
                  isDepartment = department && department.find(function (ite2) {
                    return ite2.id == departmentid;
                  });
                if (isUser || isDepartment) {
                  btns[ite].push(item);
                } else if (!user) { //没有指定用户时，所有用户允许
                  btns[ite].push(item);
                }
              }
            });
          }
        });
        this.data.where = searchWhere;
        if (repeatField.length > 0) {

          //查询重复数据
          let isRepeat = false;
          await this.getDataList().then(res=>{
            isRepeat = res
          });
          if (!isRepeat || !isRepeat.length) {
            resolve();
            return
          }
          Order_No && repeatField.unshift(Order_No);
          repeatField.push(input_time, owner_id);

          let is_addnew = btns.is_addnew.length > 0,
            is_overwrite = btns.is_overwrite.length > 0;
            this.setData({
              is_addnew,is_overwrite,showRepeat: true,repeatIndex: null,
              displayField: repeatField
            });
          wx.hideLoading();
        } else {
          resolve();
        }
      })
    },
    onRadioChange({detail}){
      this.data.repeatIndex = detail;
    },
    //取消保存
    closeRepeat(e){
      this.setData({
        showRepeat: false
      })
    },
    overwrite(){
      let {saveData,tableid,list,repeatIndex} = this.data,
        repeatData = list[repeatIndex];
      if (!repeatData){
        wx.$toast('请选择需要覆盖记录！');
      }
      saveData.entity.row_id = repeatData.row_id;
      this.setData({
        showRepeat: false
      });
      this.saveData({table:{
        table_id: tableid,
        entitys: [saveData]
      }},true);
    },
    addnew(){
      let {saveData,tableid} = this.data;
      this.setData({
        showRepeat: false
      });
      this.saveData({table:{
          table_id: tableid,
          entitys: [saveData]
      }});
    },

    getDataList(){
      let url = 'DynamicQuery/query_dynamic_v1_not_QX',
        {tableid, where,page,limit} = this.data,
        post = {"table_id": tableid,"oby": tableid + ".row_id desc",page,limit};
      if (where && where[0]){
        post.SearchWhere = where;
      }
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res => {
          let total = 0,
            {list} = this.data,
            sumArr = [],
            obj = {};
          resolve(res.data.row);
          if (res.data.row){
            total = res.data.total;
            let rows = res.data.row;
            if(page !== 1) rows = [ ...list,...rows, ]
            obj = {total,list: rows,page};
          }
          this.setData(obj);

        });
      })
    },
  //获取字段信息
    getFieldData(tableid, fieldid) {
      let url = 'QX/PRO_select_field',
        post = { "table": tableid, "fieldname": fieldid };
      return new Promise(resolve => {
        wx.$post(4,url,post).then(res=>{
          if (res.errcode != 0)return;
          resolve(res.data.row)
        })
      })
    },

    //获取模块参数
    getEntityParam(tableid){
      return new Promise(resolve => {
        wx.$post(3,'Entity_param/query_entity_param',{table_id: tableid}).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row[0];
          this.setData({entityParam: data})
          resolve(data);
        })
      })
    },
    //刷新列表
    refreshList(){
      const pages = getCurrentPages();//获取页面栈
      const beforePage = pages[pages.length - 2];  //前一个页面
      beforePage.refreshData && beforePage.refreshData();
    },

    // 获取下一审批记录
    getNextApprovalData(){
      let url = `Approval_process/my_next_approval_table_row`;
      return wx.$get(3,url,).then(res =>{
        if (res.errcode != 0) return;
        let data = res?.data?.row?.[0];
        return data;
      })
    },

    // 241227 点击编辑按钮后隐藏审批
    bindBeforeEdit(){
      this.setData({approveFlag: false})
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
      wx.$setBarTitle();
      let entity = options.entity,
        rowid = options.rid,
        status = options.status,
        obj = {
          tableid: entity,
          rowid: rowid,
          aprRowid: rowid,
          status:status,
          isDisplay: status === 'edit',
        };
      await this.getEntityParam(entity);
      if (status === 'edit') {
        if (this.data.entityParam.is_verify) {  //当前编辑界面、已启用审批
          obj.approveFlag = true;
        }
      }

      let def = wx.getStorageSync('defValue');
      if (def){
        wx.removeStorageSync('defValue');
        obj.defValue = def;
      }

      this.setData(obj);


    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})

